package com.example.administrator.ormlite_demoproject.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.example.administrator.ormlite_demoproject.db.bean.FriendsInfo;
import com.example.administrator.ormlite_demoproject.db.bean.UserInfo;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by Lzz on 9/5/2017.
 */

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
    private static final String TAG = "DatabaseHelper";
    private static final String DBNAME = "YouYuanV1.db";// 数据库名称
    private static final int VERSION = 1;// 当前数据库版本

    private static SQLiteDatabase mDB;


    public DatabaseHelper(Context context) {
        super(context, DBNAME, null, VERSION);
        Log.d(TAG, "DatabaseHelper: 创建数据库成功！");
    }


    public static synchronized SQLiteDatabase getDB(Context context) {
        if (mDB == null) {
            mDB = new DatabaseHelper(context).getWritableDatabase();
        }
        return mDB;
    }


    @Override
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
        /**
         * 在该方法中进行创建表操作
         * 使用OrmLite 框架的 TableUtils.createTable进行创建表操作。
         *eg.
         */
        try {
            TableUtils.createTableIfNotExists(connectionSource, UserInfo.class);
            database.setVersion(VERSION); // 设置数据库版本
        } catch (SQLException e) {
            e.printStackTrace();
        }


    }


    /**
     * 创建数据表 带表名
     *
     * @param db
     * @param cls
     */
    private void createTable(SQLiteDatabase db, Class<?> cls, String tableName) {

    }

    /**
     * 创建数据表
     *
     * @param db
     * @param cls
     */
    private void createTable(SQLiteDatabase db, Class<?> cls) {

    }

    /**
     * 添加表字段
     *
     * @param db
     * @param tableName
     * @param columnName
     * @param columnType
     */
    private void addColumnInTable(SQLiteDatabase db, String tableName, String columnName, String columnType) {

    }

    /**
     * 删除表
     *
     * @param db
     * @param table
     */
    private void deleteTable(SQLiteDatabase db, String table) {

    }


    /*
    * 更新数据库
    * */
    @Override
    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        try {
            updateVersion(connectionSource, oldVersion);
            database.setVersion(newVersion);
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG, "onUpgrade: "+e.getMessage());
        }
    }


    /**
     * 更新数据库操作：先删除，在创建
     *
     * @param connectionSource
     * @param oldVersion
     */
    private void updateVersion(ConnectionSource connectionSource, int oldVersion) {
        if (oldVersion < VERSION) {
            //删除表
            try {
/*                TableUtils
                        .dropTable(connectionSource, BaseModel.class, true);
                TableUtils
                        .dropTable(connectionSource, User.class, true);
                TableUtils
                        .dropTable(connectionSource, Friend.class, true);*/
            } catch (Exception e) {
                Log.d(TAG, "updateVersion: " + e.getMessage());
            }

            //创建表
            try {
/*                TableUtils
                        .createTableIfNotExists(connectionSource, BaseModel.class);
                TableUtils
                        .createTableIfNotExists(connectionSource, User.class);
                TableUtils
                        .createTableIfNotExists(connectionSource, Friend.class);
                TableUtils
                        .createTableIfNotExists(connectionSource, Group.class);*/
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }




    /**
     * 数据库表新增字段时使用
     * @param sqLiteDatabase
     * @param oldVersion
     * @throws SQLException
     */
    private void update2Version(SQLiteDatabase sqLiteDatabase,int oldVersion,Class cls,String tableName,String columnName) throws SQLException {
        if(oldVersion < VERSION){
            if (!checkColumnExist(sqLiteDatabase, tableName, columnName)) {
                Dao<FriendsInfo, String> childOne = getDao(cls);
                childOne.executeRaw("ALTER TABLE "+tableName+" ADD COLUMN "+columnName+" varchar;");
            }
        }
    }


    private boolean checkColumnExist(SQLiteDatabase db, String tableName,
                                     String columnName) {
        boolean result = false;
        Cursor cursor = null;
        try {
            // 查询一行
            cursor = db.rawQuery("SELECT * FROM " + tableName + " LIMIT 0",
                    null);
            result = cursor != null && cursor.getColumnIndex(columnName) != -1;
        } catch (Exception e) {
        } finally {
            if (null != cursor && !cursor.isClosed()) {
                cursor.close();
            }
        }
        return result;
    }





}
